package lab4;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class Student extends Thread{
    private final List<String> courses;
    private final Condition notFull, notEmpty;
    final Lock lock;

    int courseLen = 10;

    public Student(List<String> courses, Condition notFull, Condition notEmpty, Lock lock){
        this.courses = courses;
        this.notFull = notFull;
        this.notEmpty = notEmpty;
        this.lock = lock;
    }

    @Override
    public void run() {
        while (true){
            lock.lock();
            if (courses.size() > courseLen){
                try {
                    notFull.await();
                    System.out.println(getName()+"前方拥挤，请稍后再试。。。");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }else{
                courses.add(getName());
                System.out.println(getName()+"已发送选课请求。。。");
                notEmpty.signalAll();
                this.yield();
            }
            lock.unlock();
        }
    }
}
